// 分析报告页面
var analysisReport = {
    analysisId: null,
    productTable: null,
    questionTable: null,

    // 初始化
    init: function() {
        console.log('初始化分析报告页面...');
        
        // 优先从全局变量获取analysisId（SPA模式）
        if (window.currentAnalysisId) {
            this.analysisId = window.currentAnalysisId;
        } else {
            // 其次从URL参数获取（独立访问模式）
            const urlParams = new URLSearchParams(window.location.search);
            this.analysisId = urlParams.get('analysisId');
        }
        
        if (!this.analysisId) {
            Swal.fire('错误', '缺少分析ID参数', 'error').then(() => {
                this.goBack();
            });
            return;
        }
        
        // 加载数据（只加载Tab1的数据，优化首次加载速度）
        this.loadAnalysisTask();
        this.loadTaskSummary();
        
        // ⭐ 懒加载优化：不立即初始化DataTable，等点击Tab时再加载
        // this.initProductTable();
        // this.initQuestionTable();
        
        // 绑定事件
        this.bindEvents();
        this.bindTabEvents();  // ⭐ 绑定Tab切换事件
    },
    
    // 加载分析任务信息
    loadAnalysisTask: function() {
        axios.get(`/analysis/task/${this.analysisId}`)
            .then(res => {
                // 注意：axios拦截器已经返回了res（即response.data）
                const task = res.data;
                $('#analysisId').text(task.analysisId);
                $('#analysisTitle').text(task.analysisName || '分析报告');
                
                const statusBadge = this.getStatusBadge(task.analysisStatus);
                $('#analysisStatusDisplay').html(statusBadge);
            })
            .catch(err => {
                console.error('加载分析任务失败:', err);
            });
    },
    
    // 加载任务汇总（模块1）
    loadTaskSummary: function() {
        axios.get(`/analysis/summary/${this.analysisId}`)
            .then(res => {
                // 注意：axios拦截器已经返回了res（即response.data）
                const summary = res.data;
                this.renderTaskSummary(summary);
            })
            .catch(err => {
                console.error('加载任务汇总失败:', err);
                Swal.fire('错误', '加载任务汇总失败', 'error');
            });
    },
    
    // 渲染任务汇总
    renderTaskSummary: function(summary) {
        // 基础信息
        $('#totalQuestions').text(summary.totalQuestions || 0);
        $('#totalPlatforms').text(summary.totalPlatforms || 0);
        $('#totalResults').text(summary.totalResults || 0);
        $('#totalProducts').text(summary.totalProducts || 0);
        
        // 我方产品表现
        $('#ourProductMentions').text(summary.ourProductMentions || 0);
        $('#ourProductCoverageRate').text((summary.ourProductCoverageRate || 0) + '%');
        $('#ourProductAvgRanking').text(summary.ourProductAvgRanking || '-');
        $('#ourProductCount').text(summary.ourProductCount || 0);
        
        // 平台分布
        this.renderPlatformDistribution(summary.ourProductPlatformDistribution);
        
        // 竞品Top5
        this.renderTopCompetitors(summary.topCompetitors);
    },
    
    // 渲染平台分布
    renderPlatformDistribution: function(distributionJson) {
        if (!distributionJson) {
            return;
        }
        
        try {
            const distribution = JSON.parse(distributionJson);
            let html = '';
            
            for (let platform in distribution) {
                const data = distribution[platform];
                html += `
                    <tr>
                        <td><span class="badge platform-badge bg-info">${platform}</span></td>
                        <td>${data.count}次</td>
                        <td>${data.rate}%</td>
                    </tr>
                `;
            }
            
            $('#platformDistribution').html(html);
        } catch (e) {
            console.error('解析平台分布失败:', e);
        }
    },
    
    // 渲染竞品Top5
    renderTopCompetitors: function(competitorsJson) {
        if (!competitorsJson) {
            return;
        }
        
        try {
            const competitors = JSON.parse(competitorsJson);
            let html = '';
            
            competitors.forEach((item, index) => {
                html += `
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <div>
                            <strong>${item.productName}</strong>
                            <small class="text-muted ms-2">${item.brandName || ''}</small>
                        </div>
                        <span class="badge bg-primary rounded-pill">${item.count}次</span>
                    </li>
                `;
            });
            
            $('#competitorList').html(html);
        } catch (e) {
            console.error('解析竞品列表失败:', e);
        }
    },
    
    // 初始化商品表格（模块2）
    initProductTable: function() {
        const self = this;
        
        this.productTable = $('#productTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: function(data, callback) {
                axios.get(`/analysis/products/${self.analysisId}`)
                    .then(res => {
                        // 注意：axios拦截器已经返回了res（即response.data）
                        callback({ data: res.data });
                    })
                    .catch(err => {
                        console.error('加载商品列表失败:', err);
                        callback({ data: [] });
                    });
            },
            columns: [
                { 
                    data: null,
                    render: function(data, type, row, meta) {
                        return meta.row + 1;
                    }
                },
                {
                    data: 'productName',
                    render: function(data, type, row) {
                        return `<strong>${data}</strong>`;
                    }
                },
                { data: 'brandName' },
                {
                    data: null,
                    render: function(data, type, row) {
                        let badges = '';
                        if (row.isOurProduct === 1) {
                            badges += '<span class="badge bg-success me-1">我方产品</span>';
                        }
                        if (row.isCompetitor === 1) {
                            badges += '<span class="badge bg-warning">竞品</span>';
                        }
                        return badges || '-';
                    }
                },
                { data: 'totalMentions' },
                {
                    data: null,
                    render: function(data, type, row) {
                        return `${row.questionCoverage} (${row.questionCoverageRate || 0}%)`;
                    }
                },
                { data: 'avgRanking' },
                {
                    data: null,
                    render: function(data, type, row) {
                        const top3 = (row.rank1Count || 0) + (row.rank2Count || 0) + (row.rank3Count || 0);
                        return `${top3}次`;
                    }
                },
                {
                    data: null,
                    render: function(data, type, row) {
                        return `
                            <button class="btn btn-sm btn-primary view-product-detail" data-id="${row.productId}">
                                <i class="fas fa-eye"></i> 详情
                            </button>
                        `;
                    }
                }
            ],
            order: [[4, 'desc']],  // 按推荐次数倒序
            language: {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sSearch": "搜索:",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                }
            }
        });
    },
    
    // 初始化问句表格（模块3 - 带子行展开）
    initQuestionTable: function() {
        const self = this;
        
        this.questionTable = $('#questionTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: function(data, callback) {
                axios.get(`/analysis/questions/${self.analysisId}`)
                    .then(res => {
                        // 注意：axios拦截器已经返回了res（即response.data）
                        callback({ data: res.data });
                    })
                    .catch(err => {
                        console.error('加载问句列表失败:', err);
                        callback({ data: [] });
                    });
            },
            columns: [
                {
                    // 展开/收起按钮列
                    className: 'dt-control',
                    orderable: false,
                    data: null,
                    defaultContent: ''
                },
                { data: 'questionId' },
                {
                    data: 'questionContent',
                    render: function(data) {
                        return data.length > 50 ? data.substring(0, 50) + '...' : data;
                    }
                },
                { data: 'platformCount' },
                { data: 'totalProducts' },
                {
                    data: 'ourProductAppears',
                    render: function(data, type, row) {
                        if (data === 1) {
                            return `<span class="badge bg-success">是</span> (平均排名: ${row.ourProductAvgRanking || '-'})`;
                        }
                        return '<span class="badge bg-secondary">否</span>';
                    }
                },
                {
                    data: 'consistencyLevel',
                    render: function(data) {
                        if (data === '高') return '<span class="badge bg-success">高</span>';
                        if (data === '中') return '<span class="badge bg-warning">中</span>';
                        if (data === '低') return '<span class="badge bg-danger">低</span>';
                        return '-';
                    }
                },
                {
                    data: null,
                    render: function(data, type, row) {
                        return `
                            <button class="btn btn-sm btn-primary view-question-detail" data-id="${row.questionId}">
                                <i class="fas fa-eye"></i> 详情
                            </button>
                        `;
                    }
                }
            ],
            order: [[1, 'asc']],  // 改为按ID排序（第0列是展开按钮）
            language: {
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sSearch": "搜索:",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                }
            }
        });
        
        // ⭐ 绑定子行展开/收起事件
        $('#questionTable tbody').on('click', 'td.dt-control', function() {
            var tr = $(this).closest('tr');
            var row = self.questionTable.row(tr);
            
            if (row.child.isShown()) {
                // 收起子行
                row.child.hide();
                tr.removeClass('shown');
            } else {
                // 展开子行
                row.child(self.formatQuestionChildRow(row.data())).show();
                tr.addClass('shown');
            }
        });
    },
    
    // ⭐ 格式化问句子行内容（展开后显示的内容）
    formatQuestionChildRow: function(data) {
        if (!data.platformResults) {
            return '<div class="child-row-content"><p class="text-muted">暂无平台推荐数据</p></div>';
        }
        
        try {
            const platformResults = JSON.parse(data.platformResults);
            
            let html = '<div class="child-row-content">';
            
            // 遍历每个平台
            for (let platform in platformResults) {
                const products = platformResults[platform];
                
                html += `
                    <div class="platform-section">
                        <h6><span class="badge bg-info">${platform}</span></h6>
                        <div class="products-list">
                `;
                
                // 遍历该平台的商品
                products.forEach((product, index) => {
                    let itemClass = 'product-item';
                    if (product.isOurProduct) {
                        itemClass += ' our-product';
                    } else if (product.isCompetitor) {
                        itemClass += ' competitor';
                    }
                    
                    let strengthBadge = '';
                    if (product.strength === 'strong') {
                        strengthBadge = '<span class="badge-sm badge bg-danger">强推荐</span>';
                    } else if (product.strength === 'medium') {
                        strengthBadge = '<span class="badge-sm badge bg-info">中等</span>';
                    } else if (product.strength === 'weak') {
                        strengthBadge = '<span class="badge-sm badge bg-secondary">弱</span>';
                    }
                    
                    let productBadge = '';
                    if (product.isOurProduct) {
                        productBadge = '<span class="badge-sm badge bg-success">我方产品</span>';
                    } else if (product.isCompetitor) {
                        productBadge = '<span class="badge-sm badge bg-warning">竞品</span>';
                    }
                    
                    html += `
                        <div class="${itemClass}">
                            <span class="ranking-number">${product.ranking}</span>
                            <strong>${product.productName}</strong>
                            ${productBadge}
                            ${strengthBadge}
                            ${product.brandName ? '<br><small class="text-muted">' + product.brandName + '</small>' : ''}
                        </div>
                    `;
                });
                
                html += `
                        </div>
                    </div>
                `;
            }
            
            // 添加汇总信息
            html += `
                <div class="mt-3 p-2 bg-light rounded">
                    <small class="text-muted">
                        <i class="fas fa-chart-bar me-1"></i>
                        一致推荐：${data.commonProducts || 0}个 | 
                        差异商品：${data.uniqueProducts || 0}个 | 
                        一致性：${data.consistencyLevel || '-'} (${data.consistencyScore || 0}%)
                    </small>
                </div>
            `;
            
            html += '</div>';
            
            return html;
            
        } catch (e) {
            console.error('解析平台结果失败:', e);
            return '<div class="child-row-content"><p class="text-danger">数据解析失败</p></div>';
        }
    },
    
    // 绑定事件
    bindEvents: function() {
        const self = this;
        
        // 查看商品详情
        $('#productTable').on('click', '.view-product-detail', function() {
            const productId = $(this).data('id');
            self.viewProductDetail(productId);
        });
        
        // 查看问句详情
        $('#questionTable').on('click', '.view-question-detail', function() {
            const questionId = $(this).data('id');
            self.viewQuestionDetail(questionId);
        });
    },
    
    // 绑定Tab切换事件（⭐懒加载优化）
    bindTabEvents: function() {
        const self = this;
        
        // 点击商品分析Tab时，才初始化商品表格
        $('#products-tab').one('shown.bs.tab', function() {
            console.log('首次进入商品分析Tab，初始化表格...');
            self.initProductTable();
        });
        
        // 点击问句分析Tab时，才初始化问句表格
        $('#questions-tab').one('shown.bs.tab', function() {
            console.log('首次进入问句分析Tab，初始化表格...');
            self.initQuestionTable();
        });
    },
    
    // 查看商品详情
    viewProductDetail: function(productId) {
        axios.get(`/analysis/products/${this.analysisId}/${productId}`)
            .then(res => {
                // 注意：axios拦截器已经返回了res（即response.data）
                const product = res.data;
                this.showProductDetailModal(product);
            })
            .catch(err => {
                console.error('加载商品详情失败:', err);
                Swal.fire('错误', '加载商品详情失败', 'error');
            });
    },
    
    // 显示商品详情模态框
    showProductDetailModal: function(product) {
        let html = `
            <div class="row">
                <div class="col-md-12 mb-3">
                    <h5>${product.productName}</h5>
                    <p class="text-muted">品牌：${product.brandName || '-'}</p>
                    ${product.isOurProduct === 1 ? '<span class="badge bg-success">我方产品</span>' : ''}
                    ${product.isCompetitor === 1 ? '<span class="badge bg-warning">竞品</span>' : ''}
                </div>
                
                <div class="col-md-12 mb-3">
                    <h6>推荐统计</h6>
                    <table class="table table-sm">
                        <tr>
                            <td>总推荐次数</td>
                            <td><strong>${product.totalMentions}</strong></td>
                        </tr>
                        <tr>
                            <td>问句覆盖</td>
                            <td>${product.questionCoverage} (${product.questionCoverageRate || 0}%)</td>
                        </tr>
                        <tr>
                            <td>平均排名</td>
                            <td><strong>${product.avgRanking}</strong></td>
                        </tr>
                    </table>
                </div>
                
                <div class="col-md-12 mb-3">
                    <h6>排名分布</h6>
                    <table class="table table-sm">
                        <tr>
                            <td>第1名</td>
                            <td><span class="badge bg-danger">${product.rank1Count || 0}次</span></td>
                        </tr>
                        <tr>
                            <td>第2名</td>
                            <td><span class="badge bg-warning">${product.rank2Count || 0}次</span></td>
                        </tr>
                        <tr>
                            <td>第3名</td>
                            <td><span class="badge bg-info">${product.rank3Count || 0}次</span></td>
                        </tr>
                        <tr>
                            <td>4-5名</td>
                            <td>${product.rank45Count || 0}次</td>
                        </tr>
                        <tr>
                            <td>6+名</td>
                            <td>${product.rank6PlusCount || 0}次</td>
                        </tr>
                    </table>
                </div>
                
                <div class="col-md-12 mb-3">
                    <h6>推荐程度</h6>
                    <table class="table table-sm">
                        <tr>
                            <td>强推荐</td>
                            <td><span class="badge bg-success">${product.strongCount || 0}次</span></td>
                        </tr>
                        <tr>
                            <td>中等推荐</td>
                            <td><span class="badge bg-warning">${product.mediumCount || 0}次</span></td>
                        </tr>
                        <tr>
                            <td>弱推荐</td>
                            <td><span class="badge bg-secondary">${product.weakCount || 0}次</span></td>
                        </tr>
                    </table>
                </div>
            </div>
        `;
        
        Swal.fire({
            title: '商品详情',
            html: html,
            width: '800px',
            showCloseButton: true,
            confirmButtonText: '关闭'
        });
    },
    
    // 查看问句详情
    viewQuestionDetail: function(questionId) {
        axios.get(`/analysis/questions/${this.analysisId}/${questionId}`)
            .then(res => {
                // 注意：axios拦截器已经返回了res（即response.data）
                const question = res.data;
                this.showQuestionDetailModal(question);
            })
            .catch(err => {
                console.error('加载问句详情失败:', err);
                Swal.fire('错误', '加载问句详情失败', 'error');
            });
    },
    
    // 显示问句详情模态框
    showQuestionDetailModal: function(question) {
        let platformResultsHtml = '';
        
        // 解析各平台结果
        if (question.platformResults) {
            try {
                const platformResults = JSON.parse(question.platformResults);
                
                for (let platform in platformResults) {
                    const products = platformResults[platform];
                    
                    platformResultsHtml += `
                        <div class="mb-3">
                            <h6><span class="badge bg-info">${platform}</span></h6>
                            <ol class="list-group list-group-numbered">
                    `;
                    
                    products.forEach(product => {
                        let badge = '';
                        if (product.isOurProduct) {
                            badge = '<span class="badge bg-success ms-2">我方产品</span>';
                        }
                        
                        platformResultsHtml += `
                            <li class="list-group-item">
                                ${product.productName} ${badge}
                                <small class="text-muted">(${product.brandName || ''})</small>
                            </li>
                        `;
                    });
                    
                    platformResultsHtml += `
                            </ol>
                        </div>
                    `;
                }
            } catch (e) {
                console.error('解析平台结果失败:', e);
                platformResultsHtml = '<p class="text-muted">暂无数据</p>';
            }
        }
        
        let html = `
            <div class="row">
                <div class="col-md-12 mb-3">
                    <h6>问句内容</h6>
                    <p>${question.questionContent}</p>
                </div>
                
                <div class="col-md-12 mb-3">
                    <h6>汇总统计</h6>
                    <table class="table table-sm">
                        <tr>
                            <td>采集平台数</td>
                            <td>${question.platformCount}</td>
                        </tr>
                        <tr>
                            <td>识别商品数</td>
                            <td>${question.totalProducts}</td>
                        </tr>
                        <tr>
                            <td>我方产品出现</td>
                            <td>${question.ourProductAppears === 1 ? '<span class="badge bg-success">是</span>' : '<span class="badge bg-secondary">否</span>'}</td>
                        </tr>
                        <tr>
                            <td>平台一致性</td>
                            <td>${question.consistencyLevel || '-'} (${question.consistencyScore || 0}%)</td>
                        </tr>
                    </table>
                </div>
                
                <div class="col-md-12">
                    <h6>各平台推荐结果</h6>
                    ${platformResultsHtml}
                </div>
            </div>
        `;
        
        Swal.fire({
            title: '问句详情',
            html: html,
            width: '900px',
            showCloseButton: true,
            confirmButtonText: '关闭'
        });
    },
    
    // 获取状态徽章
    getStatusBadge: function(status) {
        const statusMap = {
            'pending': '<span class="badge bg-warning">待执行</span>',
            'running': '<span class="badge bg-info">执行中</span>',
            'completed': '<span class="badge bg-success">已完成</span>',
            'failed': '<span class="badge bg-danger">失败</span>'
        };
        return statusMap[status] || '<span class="badge bg-secondary">未知</span>';
    },
    
    // 返回分析列表
    goBack: function() {
        // 加载分析列表页面（SPA模式）
        if (typeof loadPage === 'function') {
            loadPage('/pages/analysis/list.html');
        } else {
            // 独立访问模式，返回首页
            window.location.href = '/index.html#analysis-list';
        }
    }
};

// 页面加载完成后初始化
$(document).ready(function() {
    analysisReport.init();
});

